//
//  CRDialogueViewController.m
//  CRChatRoom
//
//  Created by lanou3g on 15/11/21.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRDialogueViewController.h"
#import "CRDialogueFrame.h"
#import "CRDialogueCell.h"
#import "CRKeyboardView.h"
#import "CRDialogue.h"
#import "CRUserManager.h"
@interface CRDialogueViewController ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, AVIMClientDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *allDialogueFrame;
@property (nonatomic, strong) CRKeyboardView *keyboardView;
@property (nonatomic, strong) CRDialogue *dialogue;
@property (nonatomic, strong) AVUser *currentUser;
@property (nonatomic, strong) CRUserManager *manager;

@end

@implementation CRDialogueViewController
#pragma mark >>>> 懒加载
- (CRUserManager *)manager {
    if (!_manager) {
        _manager = [CRUserManager defaultManager];
        // 获取当前用户信息
        self.currentUser = [AVUser currentUser];
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self layOutSubView];
    [self layOutData];
    
//    self.otherClientID = @"564e9f5a00b0d1db33b10c47";
    
}

/**
 *  自定义控件
 */
- (void)layOutSubView
{
    
    self.title = self.friendModel.username;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - 44) style:UITableViewStylePlain];
    
    //隐藏cell之间线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //取消cell被选状态
    self.tableView.allowsSelection = NO;
    //设置背景图
    self.tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
    [self.tableView registerClass:[CRDialogueCell class] forCellReuseIdentifier:@"CRDialogueCell"];
    // 设置导航栏不透明
//    [self.navigationController.navigationBar setTranslucent:NO];
    
    //声明TableView代理
    self.tableView.dataSource = self;
    self.tableView.delegate = self;

    //初始化keyBordView
    self.keyboardView = [[CRKeyboardView alloc] initWithFrame:CGRectMake(0, self.view.height - 44, self.view.width, 44)];
    self.keyboardView.textField.delegate = self;
    [self.view addSubview:self.tableView];
//    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [self.view addSubview:self.keyboardView];
    
    // 接收消息
    [self.manager receiveMessageWithDelegate:self myClientID:self.currentUser.objectId];
}

/**
 *  数据初始化
 */
- (void)layOutData
{
    self.dialogue = [CRDialogue new];
    [self setDataWithDialogue];
    [self.keyboardView.voiceBtn addTarget:self action:@selector(voiceBtnPress:) forControlEvents:UIControlEventTouchUpInside];
    _allDialogueFrame = [NSMutableArray array];
}
/**
 *  获取服务器传会的聊天记录
 */
- (void)setDataWithDialogue
{
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"" ofType:@""]];
    
    NSString *previousTime = nil;
    for (NSDictionary *dict in array) {
        CRDialogueFrame *dialogueFrame = [[CRDialogueFrame alloc] init];
        
        CRDialogue *dialogue = [CRDialogue dialogueWithDict:dict];
        dialogueFrame.showTime = ![previousTime isEqualToString:dialogue.currentTime];
        previousTime = dialogue.currentTime;
        [_allDialogueFrame addObject:dialogueFrame];
        dialogueFrame.dialogue = dialogue;
    }
    //监听弹出键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //监听收回键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
#pragma mark >>>> 监听键盘事件

/**
 *  键盘即将显示
 */
- (void)keyBoardWillShow:(NSNotification *)notification
{
    CGRect rect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat ty = - rect.size.height;
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, ty);
    }];
}
/**
 *   键盘即将收回
 */
- (void)keyBoardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


/**
 *  按声音按键
 *
 */
- (void)voiceBtnPress:(UIButton *)voice
{
    NSString *normal;
    if (self.keyboardView.speakBtn.hidden) {
        self.keyboardView.speakBtn.hidden = NO;
        self.keyboardView.textField.hidden = YES;
        normal = @"iconfont-jianpan";
        [self.keyboardView.textField resignFirstResponder];
    }else{
        self.keyboardView.speakBtn.hidden = YES;
        self.keyboardView.textField.hidden = NO;
        normal = @"iconfont-yuyin-2";
        [self.keyboardView.textField becomeFirstResponder];
    }
    [self.keyboardView.voiceBtn setImage:[UIImage imageNamed:normal] forState:UIControlStateNormal];

}


#pragma mark >>>> TextField代理方法
/**
 *  点击textField键盘的回车按钮事件
 *
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString *content = textField.text;
    // 获取当前时间
    NSString *time = [self getTime];
    [self addContentForInterface:content time:time type:sendDType];
    
    // 发送到服务器
    [self.manager sendMessageWithMyClientID:self.currentUser.objectId otherClientID:self.friendModel.objectId Message:content];
    //随着界面聊天动态滚动至当前行
    [self scrollToLowRow];
    //清空文本内容
    self.keyboardView.textField.text = nil;
    return YES;
}



/**
 *  当前界面聊天内容
 */
- (void)addContentForInterface:(NSString *)content time:(NSString *)time type:(DialogueType)type
{
    CRDialogueFrame *dialogueFrame = [[CRDialogueFrame alloc] init];
    CRDialogue *dialogue = [[CRDialogue alloc] init];
    dialogue.content = content;
    dialogue.currentTime = time;
    
    if (type == sendDType) {
        
        AVFile *pics = [self.currentUser objectForKey:@"icon"];
        dialogue.icon = pics.url;
    } else {
        dialogue.icon = self.friendModel.iconUrl;
    }
    
//    dialogue.picture = @"king";
    dialogue.dialogueType = type;
    dialogueFrame.dialogue = dialogue;
    [_allDialogueFrame addObject:dialogueFrame];
    // 刷新列表
    [self.tableView reloadData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)Ωsection {
    return _allDialogueFrame.count;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CRDialogueCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CRDialogueCell" forIndexPath:indexPath];
    
    //设置数据
    if (_allDialogueFrame.count == 0) {
        return cell;
    }
    cell.cellFrame = self.allDialogueFrame[indexPath.row];
    return cell;
}
/**
 *  当滑动聊天界面， 键盘收回
 *
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}
/**
 *  返回cell行高
 *
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellHeight = [self.allDialogueFrame[indexPath.row] cellHeigth];
    
    return  cellHeight;
    
}


#pragma mark >>>> 其他方法
- (NSString *)getTime {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSDate *date = [NSDate date];
    //@“yyyy-MM-dd HH:mm:ss”
    formatter.dateFormat = @"HH:mm";
    return [formatter stringFromDate:date];
}

- (void)scrollToLowRow {
    //随着界面聊天动态滚动至当前行
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.allDialogueFrame.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
#pragma mark >>>> 接收消息的回调方法
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message {
    
    NSLog(@"+++++++++++++++%@", message.text);
    NSString *time = [self getTime];
    [self addContentForInterface:message.text time:time type:receiveDType];
    
}
@end
